"use client"

import Search from '@/components/Search'
import { useSearchParams } from 'next/navigation'
import { useSuspenseQuery, useQuery } from '@tanstack/react-query'
import { Suspense, useState, lazy, useEffect } from 'react'
import { 
    Spin, 
    Skeleton, 
    Pagination,
    message, 
} from 'antd'
import SearchResultCard from '@/components/SearchResultCard'
import RelevantResult from '@/components/RelevantResult'
import NotFound from '@/components/NotFound'
import { apiClient } from '@/lib/apiClient'
import { arrayHelper, fillValueHelper } from '@/utils/common'

const ReactQueryDevtoolsProduction = lazy(() =>
  import('@tanstack/react-query-devtools/build/modern/production.js').then(
    (d) => ({
      default: d.ReactQueryDevtools,
    }),
  ),
)

function useWaitQuery({ content, pageNum, pageSize }) {
    const query = useSuspenseQuery({
        queryKey: ['search', content, pageNum, pageSize],
        queryFn: async () => {
            const searchPromise = apiClient.post(
                `home/search`,
                { 
                    json: {
                        content: content,
                        pageNum: pageNum,
                        pageSize: pageSize,
                    } 
                }
            ).json()

            const RecommendationRelevantPromise = apiClient.post(
                `home/relatedCitizen`,
                { 
                    json: {
                        content: content,
                        pageNum: pageNum,
                        pageSize: pageSize,
                    } 
                }
            ).json()

            const result = await Promise.allSettled([searchPromise, RecommendationRelevantPromise])
            return result
        }
    })

    return [query.data, query]
}

function listHelper (result, type) {

    let value = []
    let total = 0

    if (result.status === 'fulfilled' && result?.value.code === 200) {
        if (type === 'search') {
            value = arrayHelper(result?.value.data?.list).map((item) => {
                return {
                    name: item?.citizenInfo?.name,
                    age: `${fillValueHelper(item?.citizenInfo?.age)}`,
                    ethnic: item?.citizenInfo?.nation,
                    placeOfRegion: item?.citizenInfo?.nativePlace,
                    idNumber: `${item?.citizenInfo?.idCard}`,
                    url: `${item?.citizenInfo?.idCard}`,
                    avatarUrl: item?.citizenInfo?.avatarUrl,
                    educationalBackground: item?.citizenInfo?.education,
                    gender: item?.citizenInfo?.gender,
                    phoneList: arrayHelper(item?.phoneList).map((phoneItem) => (phoneItem?.phone)).slice(0, 3),
                    tagList: arrayHelper(item?.tagList).map((tagItem) => {
                        return {
                            name: tagItem?.tagName,
                        }
                    }).slice(0, 4),
                    connectionList: arrayHelper(item?.relationList).map((relationItem) => {
                        return {
                            name: relationItem?.name,
                            url: `/${relationItem?.idCard}`,
                            avatarUrl: relationItem?.avatarUrl,
                            note: arrayHelper(relationItem?.relationshipList),
                        }
                    }),
                    note: item?.citizenInfo?.relationName,
                }
            })
            total = result?.value.data?.total
        }

        if (type === 'relevant') {
            value = arrayHelper(result?.value.data).map((item) => {
                return {
                    name: item?.citizenInfo?.name,
                    age: `${fillValueHelper(item?.citizenInfo?.age)}`,
                    ethnic: item?.citizenInfo?.nation,
                    placeOfRegion: item?.citizenInfo?.nativePlace,
                    idNumber: `${item?.citizenInfo?.idCard}`,
                    url: `${item?.citizenInfo?.idCard}`,
                    avatarUrl: item?.citizenInfo?.avatarUrl,
                    educationalBackground: item?.citizenInfo?.education,
                    gender: item?.citizenInfo?.gender,
                    phoneList: arrayHelper(item?.phoneList).map((phoneItem) => (phoneItem?.phone)).slice(0, 3),
                    tagList: arrayHelper(item?.tagList).map((tagItem) => {
                        return {
                            name: tagItem?.tagName,
                        }
                    }),
                    connectionList: arrayHelper(item?.relationList).map((relationItem) => {
                        return {
                            name: relationItem?.name,
                            url: `/${relationItem?.idCard}`,
                            avatarUrl: relationItem?.avatarUrl,
                            note: arrayHelper(relationItem?.relationshipList),
                        }
                    }),
                    note: item?.citizenInfo?.relationName,
                }
            })
        }
    }

    if (result.status === 'rejected') {
        console.error(result.reason)
        
        if (typeof document !== 'undefined') {
            // message.error(result.reason.name)
        }
    }

    return {
        value,
        total,
    }
}

function Result ({ handleGetTotalResultCount }) {

    const searchParams = useSearchParams()

    const [currentPage, setCurrentPage] = useState(() => (1))

    const [result] = useWaitQuery({
        content: searchParams.get('q'),
        pageNum: currentPage,
        pageSize: 10,
    })

    const searchResult = listHelper(result[0], 'search')
    const relevantResult = listHelper(result[1], 'relevant')

    // handleGetTotalResultCount(searchResult.total)

    const onPageChange = (page) => {
        setCurrentPage(() => (page))
    }

    return (
        <div className='bg-white px-6 flex'>
            {
                searchResult.value.length > 0
                    ? (
                        <div className='ml-[164px] mt-2'>
                            {searchResult.value.map((item, index) => {
                                return (
                                    <SearchResultCard
                                        key={index}
                                        name={item.name}
                                        age={item.age}
                                        ethnic={item.ethnic}
                                        placeOfRegion={item.placeOfRegion}
                                        idNumber={item.idNumber}
                                        educationalBackground={item.educationalBackground}
                                        gender={item.gender}
                                        phoneList={item.phoneList}
                                        tagList={item.tagList}
                                        connectionList={item.connectionList}
                                        url={item.url}
                                        avatarUrl={item.avatarUrl}
                                    />
                                )
                            })}
                            <Pagination 
                                current={currentPage} 
                                total={searchResult.total}
                                showSizeChanger={false} 
                                style={{ paddingBottom: '16px' }}
                                onChange={onPageChange}
                            />
                        </div>
                    )
                    : null
            }
            {
                searchResult.value.length > 0 && relevantResult.value.length > 0
                    ? (
                        <div className='ml-8'>
                            <RelevantResult list={relevantResult.value}/>
                        </div>
                    )
                    : null
            }
            {
                searchResult.value.length <= 0
                    ? (
                        <div className='ml-[164px] mt-2'>
                            <NotFound text={searchParams.get('q')} />
                        </div>
                    )
                    : null
            }
        </div>
    )
}

function Loading() {
    return (
        <div className='flex justify-center mt-6 ml-[176px] flex-col'>
            <Skeleton active/>
            <Skeleton active className='mt-5'/>
        </div>
    )
}

export default function Detail() {

    const searchParams = useSearchParams()
    const [total, setTotal] = useState(() => (0))

    const handleGetTotalResultCount = (total) => {
        setTotal(() => (total))
    }

    const [showDevtools, setShowDevtools] = useState(false)

    useEffect(() => {
        window.toggleDevtools = () => setShowDevtools((old) => !old)
    }, [])

    return (
        <div className='bg-white m-3 pb-6 rounded-md' style={{ height: 'calc(100% - 96px)' }}>
            <Suspense>
                <div className="px-6">
                    <Search 
                        type='horizontal' 
                        value={searchParams.get('q')}
                        // resultCount={total}
                    />
                </div>
            </Suspense>
            <Suspense fallback={(<Loading />)}>
                <Result 
                    // handleGetTotalResultCount={handleGetTotalResultCount}
                />
            </Suspense>
            {showDevtools && (
                <Suspense fallback={null}>
                    <ReactQueryDevtoolsProduction />
                </Suspense>
            )}
        </div>
    )
}